package com.kehao.leetcode.jzoffer;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Kehao.Chen
 * @version 1.0
 * @date 2022/6/30 16:32
 */
public class JZSolution044 {

    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> largestValues(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        largestValues(root,0,result);
        return result;
    }

    private void largestValues(TreeNode root, int level, List<Integer> result) {
        if(root==null) return;
        if(result.size()<=level){
            result.add(level,root.val);
        }else if(root.val>result.get(level)){
            result.set(level,root.val);
        }
        largestValues(root.left,level+1,result);
        largestValues(root.right,level+1,result);
    }

    @Test
    public void test01(){
        Integer[] root = {1,3,2,5,3,null,9};
        TreeNode rootNode = buildTree(root);
        List<Integer> list = largestValues(rootNode);
        System.out.println(list);
    }

    @Test
    public void test02(){
        Integer[] root = {1,2,3};
        TreeNode rootNode = buildTree(root);
        List<Integer> list = largestValues(rootNode);
        System.out.println(list);
    }

    private TreeNode buildTree(Integer[] treeArray){
        TreeNode[] treeNodeList = new TreeNode[treeArray.length];
        for (int i = 0; i < treeArray.length; i++) {
            if(treeArray[i]!=null){
                treeNodeList[i] = new TreeNode(treeArray[i]);
            }
        }
        for (int i = 0; i < treeNodeList.length/2; i++) {
            treeNodeList[i].left = treeNodeList[i*2+1];
            treeNodeList[i].right = treeNodeList[i*2+2];
        }
        return treeNodeList[0];
    }
}
